//
//  NetWorkCache.swift
//  Edaixi-iOS
//
//  Created by 刘树华 on 2017/12/5.
//  Copyright © 2017年 刘树华. All rights reserved.
//

import Foundation

class NetWorkCache : NSObject {
   
    static let Shared = {()->NetWorkCache in
        let cache = NetWorkCache()
         let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        
        do {
          let isE =  FileManager.default.fileExists(atPath: path+"/"+"NetWorkCache")
            if !isE{
               try FileManager.default.createDirectory(atPath: path+"/"+"NetWorkCache", withIntermediateDirectories: false, attributes: nil)
            }
           
        }catch let err {
            MYDebugPrintf(msg: err)
        }
        return cache
    }()
    func stroreResponse(forRequest key : String , value : String)  {
        
        let valueData = value.data(using: .utf8)
        guard let da = valueData else {
            return
        }
       let baseData = da.base64EncodedData()
        
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
       let fileUrl = URL(fileURLWithPath: path+"/NetWorkCache/"+key)
        do {
            try baseData.write(to: fileUrl)
        }catch let err {
            MYDebugPrintf(msg: err)
        }

//        let dic = [key:value]
//       let nsdic =  NSDictionary(dictionary: dic)
//
//      let issuccess = nsdic.write(toFile:path+"/NetWorkCache/"+key, atomically: true)
//        MYDebugPrintf(msg: "写入\(issuccess)")
    }
    func reponse(forRequest key : String) -> String? {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
       let  fileUrl = URL(fileURLWithPath: path+"/NetWorkCache/"+key)
        
      let valueData = try? Data(contentsOf: fileUrl)
        
        guard let value = valueData else {
            return nil
        }
        guard let val =  Data(base64Encoded: value) else {
            return nil
        }
       
       return String(data: val, encoding: .utf8)
//        if let nsdic =  NSDictionary(contentsOfFile: path+"/NetWorkCache/"+key){
//
//         return nsdic.object(forKey: key) as? String
//
//        }else{
//            return nil
//        }
    }
    
}
